import requests
from flask_restful import Resource

from common.db import ProxyData
from common.utilFunction import getHtmlTree


class Proxy(Resource):
    @staticmethod
    def get():
        from run import session
        get_proxy(session)


def get_proxy(session):
    for i in range(10):
        tree = getHtmlTree("http://www.kuaidaili.com/free/inha/" + str(i) + "/")
        proxy_list = tree.xpath('//*[@id="list"]/table/tbody/tr')
        for proxy in proxy_list:
            proxy = ':'.join(proxy.xpath('./td/text()')[0:2])
            print(proxy)
            if valid_proxy(proxy):
                print("可用")
                proxyData = ProxyData()
                proxyData.proxy = proxy
                proxyData.isValid = True
                session.add(proxyData)
                try:
                    session.commit()
                except:
                    session.rollback()


def valid_proxy(proxy):
    proxies = {"http": "http://{proxy}".format(proxy=proxy),
               "https": "https://{proxy}".format(proxy=proxy)}
    try:
        r = requests.get('https://www.tmall.com/', proxies=proxies, timeout=8, verify=False)
        if r.status_code == 200:
            return True
        else:
            return False
    except Exception as e:
        print(e)
        return False
